package top.cardone.data.action;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.io.Resource;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.util.action.Action0;
import top.cardone.data.service.CrudService;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yao hai tao on 2016/4/18.
 */
@Log4j2
public class InitDataAction implements Action0 {
    @Setter
    private Resource[] jsonFiles;

    @Setter
    private String serviceBeanId;

    @Setter
    private boolean reinit = false;

    @Override
    public void action() {
        if (ArrayUtils.isEmpty(jsonFiles)) {
            return;
        }

        for (Resource jsonFile : jsonFiles) {
            if (!jsonFile.exists()) {
                continue;
            }

            try {
                String lockFilePath = jsonFile.getFile().getPath() + ".lock";

                File lockFile = new File(lockFilePath);

                if (!reinit && lockFile.exists()) {
                    continue;
                }

                String json = FileUtils.readFileToString(jsonFile.getFile(), Charsets.UTF_8);

                List<Map<String, Object>> saveMapList = ApplicationContextHolder.getBean(Gson.class).fromJson(json, new TypeToken<List<LinkedHashMap<String, Object>>>() {
                }.getType());

                ApplicationContextHolder.func(CrudService.class, service -> service.saveList(Lists.newArrayList(saveMapList)), serviceBeanId);

                FileUtils.write(lockFile, DateFormatUtils.format(new Date(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
